﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;

public partial class PromoterCoordinator : WebPageBase
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request["Id"] != null)
            {
                int id = int.Parse(Request["Id"].ToString());
                Interview interview = db.Interviews.First(u => u.IdInterview == id);
                if (interview != null)
                {
                    HiddenFieldIdInterview.Value = interview.IdInterview.ToString();

                    if (interview.TrainingCommitmentDate.HasValue)
                    {
                        TextBoxTrainingCommitmentDate.Text = String.Format("{0:dd/MM/yyyy}",interview.TrainingCommitmentDate.Value);
                    }
                    DropDownListTurn.SelectedValue = interview.Turn;
                                                       
                    
                    //Datos
                    TextBoxPromoterName.Text = interview.PromoterName;
                    TextBoxPromoterSurname1.Text = interview.PromoterSurname1;
                    TextBoxPromoterSurname2.Text = interview.PromoterSurname2;
                    //
                    TextBoxDateBirth.Text = (interview.PromoterDateBirth.HasValue) ? String.Format("{0:dd/MM/yyyy}", interview.PromoterDateBirth.Value) : string.Empty;
                    DropDownListPromoterTypeDocument.SelectedValue = interview.PromoterDocumentType;// RepresentativeDocumentType;
                    TextBoxPromoterDNI.Text = interview.PromoterDNI;
                    TextBoxPromoterRUC.Text = interview.PromoterRUC;
                    DropDownListVia.SelectedItem.Text = interview.Via;
                    TextBoxAddress.Text = interview.Address;

                    if (interview.DistrictId.HasValue)
                    {
                        DropDownListDistrict.SelectedValue = interview.District.DistrictId.ToString();
                    }
                    if (interview.Type.HasValue)
                    {
                        DropDownListType.SelectedValue = interview.Type.Value.ToString();
                    }
                    TextBoxEmail.Text = interview.Email;
                    TextBoxHomePhone.Text = interview.HomePhone;
                    TextBoxCellPhone.Text = interview.CellPhone;

                    // Información Académica
                    if (interview.UniversityId.HasValue)
                    {
                        DropDownListUniversity.SelectedValue = interview.University.UniversityId.ToString();
                    }

                    TextBoxUniversityOther.Text = interview.UniversityOther;

                    if (interview.FacultyId.HasValue)
                    {
                        DropDownListFaculty.SelectedValue = interview.Faculty.FacultyId.ToString();
                    }

                    if (interview.CollegeId.HasValue)
                    {
                        DropDownListCollege.SelectedValue = interview.College.CollegeId.ToString();
                    }

                    TextBoxFacultyCollegeOther.Text = interview.FacultyCollegeOther;
                    TextBoxCycle.Text = interview.Cycle.ToString();

                    //En caso sea menor de edad
                    TextBoxRepresentativeName.Text = interview.RepresentativeName;
                    TextBoxRepresentativeSurname1.Text = interview.RepresentativeSurname1;
                    TextBoxRepresentativeSurname2.Text = interview.RepresentativeSurname2;
                    DropDownListRepresentativeTypeDocument.SelectedValue = interview.RepresentativeDocumentType;
                    TextBoxRepresentativeDNI.Text = interview.RepresentativeDNI;
                    TextBoxRepresentativeRUC.Text = interview.RepresentativeRUC;

                    //Entrevista
                    TextBoxInterviewDate.Text = (interview.InterviewDate.HasValue) ? String.Format("{0:dd/MM/yyyy}", interview.InterviewDate.Value) : string.Empty;
                    TextBoxObservation.Text = interview.Observation;
                    DropDownListInterviewTime.SelectedValue = (interview.InterviewDate == null) ? "1" : interview.InterviewDate.Value.ToShortTimeString(); //PREGUNTAR

                    //Asignación
                    //if (base.UserSystem.RoleId == 3)
                    //{
                    //    ShowCoordinator(interview);
                    //}
                    //if (base.UserSystem.RoleId == 4)
                    //{
                    //    ShowLider(interview);
                    //}
                    if (base.UserSystem.RoleId == 2 || base.UserSystem.RoleId == 1)
                    {
                        ShowCoordinator(interview);
                        ShowLider(interview);
                    }

                    if (String.IsNullOrEmpty(interview.PointSale))
                    {
                        DropDownListPointSale.SelectedValue = interview.PointSale;
                    }   
                    DropDownListStatus.SelectedValue = interview.Status;

                    //
                    if (String.IsNullOrEmpty(interview.RepresentativeDNI) && String.IsNullOrEmpty(interview.RepresentativeName))
                    {
                        trRowRepresentative01.Visible = false;
                        trRowRepresentative02.Visible = false;
                        trRowRepresentative03.Visible = false;
                        trRowRepresentative04.Visible = false;
                        trRowRepresentative05.Visible = false;
                        TextBoxRepresentativeDNI.Enabled = false;
                    }
                    else //ML: Se adiciono para el caso que se haya puesto un promotor menor pero sin representante
                    {
                        IFormatProvider culture = new System.Globalization.CultureInfo("ES-pe", true);
                        DateTime dateBirth = DateTime.Parse(TextBoxDateBirth.Text, culture, System.Globalization.DateTimeStyles.AssumeLocal);
                        
                        if (TextBoxDateBirth.Text != null)
                        {
                            if (dateBirth > DateTime.Now.AddYears(-18) || DropDownListPromoterTypeDocument.SelectedValue.Equals("CE"))
                            {
                                trRowRepresentative01.Visible = true;
                                trRowRepresentative02.Visible = true;
                                trRowRepresentative03.Visible = true;
                                trRowRepresentative04.Visible = true;
                                trRowRepresentative05.Visible = true;

                                TextBoxRepresentativeDNI.Enabled = false;
                            }
                            else
                            {
                                trRowRepresentative01.Visible = false;
                                trRowRepresentative02.Visible = false;
                                trRowRepresentative03.Visible = false;
                                trRowRepresentative04.Visible = false;
                                trRowRepresentative05.Visible = false;

                                TextBoxRepresentativeDNI.Enabled = false;
                            }
                         }
                    }

                    if (interview.CoordinatorId.HasValue)
                    {
                        DropDownListCoordinator.SelectedValue = interview.CoordinatorId.Value.ToString();
                    }
                    if (interview.LiderId.HasValue)
                    {
                        DropDownListLider.SelectedValue = interview.LiderId.Value.ToString();
                    }
                }
            }
        }
    }

    public void ShowCoordinator(Interview interview)
    {
        DropDownListCoordinator.DataBind();
        DropDownListCoordinator.Visible = false;
        if (interview.CoordinatorId.HasValue)
        {
            UserQ userCoordinator = db.UserQs.First(u => u.Id == interview.CoordinatorId.Value);
            LiteralCoordinator.Text = userCoordinator.Name + " " + userCoordinator.Surname1 + " " + userCoordinator.Surname2;
        }
    }

    public void ShowLider(Interview interview)
    {
        if (DropDownListCoordinator.SelectedIndex != -1)
        {
            DropDownListLider.DataBind();
        }

        DropDownListLider.Visible = false;

        if (interview.LiderId.HasValue)
        {
            UserQ userLider = db.UserQs.First(u => u.Id == interview.LiderId.Value);
            LiteralLider.Text = userLider.Name + " " + userLider.Surname1 + " " + userLider.Surname2;
        }
    }

    protected void ButtonPromoter_Click(object sender, EventArgs e)
    {
        try
        {
            int id = int.Parse(HiddenFieldIdInterview.Value);
            Interview interview = db.Interviews.First(u => u.IdInterview == id);
            
            //ML:Se adiciono para edición
            Interview interviewPromoter = db.Interviews.Where(u => u.PromoterDNI.Equals(TextBoxPromoterDNI.Text)).FirstOrDefault();
            Interview interviewRepresentative =
            db.Interviews.Where(u => u.RepresentativeDNI.Equals(TextBoxRepresentativeDNI.Text) && !u.RepresentativeDNI.Equals(String.Empty)).FirstOrDefault();

            IFormatProvider culture = new System.Globalization.CultureInfo("ES-pe", true);
            DateTime dateBirth = DateTime.Parse(TextBoxDateBirth.Text, culture, System.Globalization.DateTimeStyles.AssumeLocal);

            if (dateBirth > DateTime.Now.AddYears(-18) || DropDownListPromoterTypeDocument.SelectedValue.Equals("CE"))
            {
                if (trRowRepresentative01.Visible && trRowRepresentative02.Visible && trRowRepresentative03.Visible &&
                            trRowRepresentative04.Visible && trRowRepresentative05.Visible)
                {
                    TextBoxRepresentativeDNI.Enabled = true;

                    if (String.IsNullOrEmpty(TextBoxRepresentativeName.Text.Trim()) ||
                            String.IsNullOrEmpty(TextBoxRepresentativeSurname1.Text.Trim()) ||
                            String.IsNullOrEmpty(TextBoxRepresentativeSurname2.Text.Trim()) ||
                            String.IsNullOrEmpty(TextBoxRepresentativeDNI.Text.Trim()))
                    {

                        Message1.Message = "El postulante es menor de edad o tiene carnet de extranjería, registre los datos del representante.";
                        Message1.Type = Constant.MESSAGE_ERROR;

                        trRowRepresentative01.Visible = true;
                        trRowRepresentative02.Visible = true;
                        trRowRepresentative03.Visible = true;
                        trRowRepresentative04.Visible = true;
                        trRowRepresentative05.Visible = true;

                        TextBoxRepresentativeDNI.Enabled = true;
                        LimpiarCajas();
                        return;
                    }
                    else
                    {
                        if (interviewRepresentative != null)
                        {
                            Message1.Message = "El DNI del representante ya ha sido registrado.";
                            Message1.Type = Constant.MESSAGE_ERROR;
                            return;
                        }
                    }
                }
                else
                {
                    trRowRepresentative01.Visible = true;
                    trRowRepresentative02.Visible = true;
                    trRowRepresentative03.Visible = true;
                    trRowRepresentative04.Visible = true;
                    trRowRepresentative05.Visible = true;

                    TextBoxRepresentativeDNI.Enabled = true;

                    LimpiarCajas();

                    return;
                }
            }
            

            //Grabar
            //interview.IdInterview = interviewId;
            interview.PromoterName = TextBoxPromoterName.Text;
            interview.PromoterSurname1 = TextBoxPromoterSurname1.Text;
            interview.PromoterSurname2 = TextBoxPromoterSurname2.Text;
            interview.PromoterDocumentType = DropDownListPromoterTypeDocument.SelectedValue;
            interview.PromoterRUC = TextBoxPromoterRUC.Text;
            interview.PromoterDNI = TextBoxPromoterDNI.Text;
            interview.PromoterDateBirth = dateBirth;

            interview.RepresentativeName = TextBoxRepresentativeName.Text;
            interview.RepresentativeSurname1 = TextBoxRepresentativeSurname1.Text;
            interview.RepresentativeSurname2 = TextBoxRepresentativeSurname2.Text;
            interview.RepresentativeDocumentType = DropDownListRepresentativeTypeDocument.SelectedValue;
            interview.RepresentativeRUC = TextBoxRepresentativeRUC.Text;
            interview.RepresentativeDNI = TextBoxRepresentativeDNI.Text;

            interview.Email = TextBoxEmail.Text;
            interview.UniversityId = int.Parse(DropDownListUniversity.SelectedValue);
            interview.UniversityOther = TextBoxUniversityOther.Text;

            interview.FacultyId = int.Parse(DropDownListFaculty.SelectedValue);
            interview.CollegeId = int.Parse(DropDownListCollege.SelectedValue);
            interview.FacultyCollegeOther = TextBoxFacultyCollegeOther.Text;

            interview.Cycle = TextBoxCycle.Text;
            interview.Via = DropDownListVia.SelectedValue;
            interview.Address = TextBoxAddress.Text;
            interview.DistrictId = int.Parse(DropDownListDistrict.SelectedValue);

            interview.HomePhone = TextBoxHomePhone.Text;
            interview.CellPhone = TextBoxCellPhone.Text;

            //interview.InterviewDate = Convert.ToDateTime(TextBoxInterviewDate.Text + " " + DropDownListInterviewTime.SelectedValue);
            interview.InterviewDate = DateTime.Parse(TextBoxInterviewDate.Text + " " + DropDownListInterviewTime.SelectedValue, 
                                                            culture, System.Globalization.DateTimeStyles.AssumeLocal);
            interview.Observation = TextBoxObservation.Text;

            interview.Mode = "UNIV"; //PREGUNTAR

            //interview.TrainingCommitmentDate = Convert.ToDateTime(TextBoxTrainingCommitmentDate.Text);
            interview.TrainingCommitmentDate = DateTime.Parse(TextBoxTrainingCommitmentDate.Text,
                                                            culture, System.Globalization.DateTimeStyles.AssumeLocal);
            interview.Turn = DropDownListTurn.SelectedValue;
            interview.Status = DropDownListStatus.SelectedValue;

            if (base.UserSystem.RoleId == 4)
            {
                interview.CoordinatorId = int.Parse(DropDownListCoordinator.SelectedValue);
            }
            if (base.UserSystem.RoleId == 3)
            {
                interview.LiderId = int.Parse(DropDownListLider.SelectedValue);
            }

            interview.PointSale = DropDownListPointSale.SelectedValue;
            interview.Type = Convert.ToChar(DropDownListType.SelectedValue);

            db.SubmitChanges();

            Response.Redirect("Promoter.aspx");

        }
        catch (Exception ex)
        {
            Message1.Message = "Error de sistema: " + ex.Message;
            Message1.Type = Constant.MESSAGE_ERROR;
        }
    }

    private void LimpiarCajas()
    {
        TextBoxRepresentativeName.Text = string.Empty;
        TextBoxRepresentativeSurname1.Text = string.Empty;
        TextBoxRepresentativeSurname2.Text = string.Empty;
        TextBoxRepresentativeDNI.Text = string.Empty;
        TextBoxRepresentativeRUC.Text = string.Empty;
    }


    protected void DropDownListCoordinator_DataBound(object sender, EventArgs e)
    {
        if (DropDownListCoordinator.Items.Count > 0)
        {
            for (int i = 0; i < DropDownListCoordinator.Items.Count; i++)
            {
                UserQ user = db.UserQs.First(u => u.Id == int.Parse(DropDownListCoordinator.Items[i].Value));
                DropDownListCoordinator.Items[i].Text = user.Name + " " + user.Surname1 + " " + user.Surname2;
            }

        }
    }

    protected void DropDownListLider_DataBound(object sender, EventArgs e)
    {
        if (DropDownListLider.Items.Count > 0)
        {
            for (int i = 0; i < DropDownListLider.Items.Count; i++)
            {
                UserQ user = db.UserQs.First(u => u.Id == int.Parse(DropDownListLider.Items[i].Value));
               
                if (user.UniversityId != null)
                {
                    University university = db.Universities.First(u => u.UniversityId == user.UniversityId);
                    DropDownListLider.Items[i].Text = user.Name + " " + user.Surname1 + " " + user.Surname2 + " (" + university.Name + ")";
                }
                else
                {
                    DropDownListLider.Items[i].Text = user.Name + " " + user.Surname1 + " " + user.Surname2;
                }
            }

        }
    }

    protected void DropDownListPromoterTypeDocument_SelectedIndexChanged(object sender, EventArgs e)
    {
        //if (DropDownListPromoterTypeDocument.SelectedValue.Equals("CE"))
        //{
        //    TextBoxPromoterDNI.MaxLength = 9;
        //}
        //else
        //{
        //    TextBoxPromoterDNI.MaxLength = 8;
        //}
    }

    protected void DropDownListRepresentativeTypeDocument_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (DropDownListRepresentativeTypeDocument.SelectedValue.Equals("CE"))
        {
            TextBoxRepresentativeDNI.MaxLength = 9;
        }
        else
        {
            TextBoxRepresentativeDNI.MaxLength = 8;
        }
    }
}
